/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package datacoletor;

import filesJavacc.Adder;
import filesJavacc.ParseException;
import filesJavacc.TokenMgrError;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.*;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StatisticalBarRenderer;
import org.jfree.chart.renderer.xy.XYSplineRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.statistics.DefaultStatisticalCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleInsets;

/**
 *
 * @author Heitor
 */
public class GeneratorGraphs extends javax.swing.JFrame {

    Adder ad;
    String text;
    
    /**
     * Creates new form GeneratorGraphs
     */
    public GeneratorGraphs(String s){
        
        initComponents();
        setVisible(false);
        
        this.text = s;
    }

    public void start() throws TokenMgrError, FileNotFoundException, IOException, ParseException {
        ad = new Adder(text);
        featuresBackupGateway();
        setTitle("Analise de dados");
        
        setLocationRelativeTo(null);
        setVisible(true);
    }
    
    private void featuresBackupGateway(){
    
        jComboBox1.removeAllItems();
        
        //Adicionando os itens para selecionar - os tipos de graficos
        jComboBox1.addItem("Temperatura Atual");
        jComboBox1.addItem("Congestionamento da fila");
        jComboBox1.addItem("Consumo de Energia");
        jComboBox1.addItem("Latencia");
        
        jComboBox1.addItem("Confiabilidade");
        
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        backupGateway = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Escolha o grafico desejado");

        jButton1.setText("Gerar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 316, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout backupGatewayLayout = new javax.swing.GroupLayout(backupGateway);
        backupGateway.setLayout(backupGatewayLayout);
        backupGatewayLayout.setHorizontalGroup(
            backupGatewayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backupGatewayLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 196, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        backupGatewayLayout.setVerticalGroup(
            backupGatewayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(backupGatewayLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(backupGatewayLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox1)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jTabbedPane1.addTab("Backup Gateway", backupGateway);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        processChoice(jComboBox1.getSelectedItem().toString());
        
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel backupGateway;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    // End of variables declaration//GEN-END:variables

    private void processChoice(String choice) {
        
        switch (choice) {
            case "Temperatura Atual":
                {
                    try {
                        ad.showStatCur();
                    } catch (TokenMgrError ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (FileNotFoundException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (IOException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (ParseException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    }
                    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
                    for(int j=0; j< ad.getsStatCurList().get(0).getidList().size(); j++){
                        dataset.setValue(Integer.parseInt(ad.getsStatCurList().get(0).gettempList().get(j)), 
                                "Temperatura", ad.getsStatCurList().get(0).getidList().get(j) + "Id");
                    }
                    JFreeChart chart = ChartFactory.createBarChart("Temperatura Atual nos ultimos " 
                            + ad.getsStatCurList().get(0).getTime().toString() + " segundos",
                            "Dispositivos", "Temperatura (ºC)", dataset, 
                            PlotOrientation.VERTICAL, false, true, false);
                    CategoryPlot p = chart.getCategoryPlot();
                    p.setRangeGridlinePaint(Color.black);
                    //Colocando em um painel do proprio swing java
                    ChartPanel CP = new ChartPanel(chart);
                    jPanel1.removeAll();
                    jPanel1.setLayout(new java.awt.BorderLayout());
                    jPanel1.add(CP,BorderLayout.CENTER);
                    jPanel1.validate();
                    break;
                }
            case "Congestionamento da fila":
                {
                    try {
                        ad.showStatCur();
                    } catch (TokenMgrError ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (FileNotFoundException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (IOException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (ParseException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    }
                    final DefaultStatisticalCategoryDataset dataset = new DefaultStatisticalCategoryDataset();
                    for(int j=0; j< ad.getsStatCurList().get(0).getidList().size(); j++){
                        dataset.add(Float.parseFloat(ad.getsStatCurList().get(0).getavqList().get(j)),
                                (Float.parseFloat(ad.getsStatCurList().get(0).getmxqList().get(j)) - 
                                    Float.parseFloat(ad.getsStatCurList().get(0).getavqList().get(j))),
                                "Tamanho medio da fila", ad.getsStatCurList().get(0).getidList().get(j) + "Id");
                    }
                    final CategoryAxis xAxis = new CategoryAxis("Dispositivos");
                    //xAxis.setLowerMargin(0.01d); // percentage of space before first bar
                    //xAxis.setUpperMargin(0.01d); // percentage of space after last bar
                    //xAxis.setCategoryMargin(0.05d); // percentage of space between categories
                    final ValueAxis yAxis = new NumberAxis("Tamanho");
                    // define the plot
                    final CategoryItemRenderer renderer = new StatisticalBarRenderer();
                    final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer);
                    final JFreeChart chart = new JFreeChart("Congestionamento nos ultimos " + ad.getsStatCurList().get(0).getTime()
                            + " segundos", new Font("Helvetica", Font.BOLD, 14),
                            plot, true);
                    //Colocando em um painel do proprio swing java
                    ChartPanel CP = new ChartPanel(chart);
                    jPanel1.removeAll();
                    jPanel1.setLayout(new java.awt.BorderLayout());
                    jPanel1.add(CP,BorderLayout.CENTER);
                    jPanel1.validate();
                    break;
                }
            case "Consumo de Energia":
                {
                    try {
                        ad.showStatCur();
                    } catch (TokenMgrError ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (FileNotFoundException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (IOException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (ParseException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    }
                    final DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
                    final DefaultCategoryDataset dataset2 = new DefaultCategoryDataset();
                    for(int j=0; j< ad.getsStatCurList().get(0).getidList().size(); j++){
                        char[] nomeArray = ad.getsStatCurList().get(0).getchgList().get(j).toCharArray();
                        System.out.println("Chg: " + ad.getsStatCurList().get(0).getchgList().get(j));
                        if (nomeArray.length != 0){
                            if(nomeArray[nomeArray.length-1] == 'k'
                                    | nomeArray[nomeArray.length-1] == 'K'){
                                String aux = "";
                                for(int k=0; k<nomeArray.length-1; k++){
                                    aux = aux.concat(Character.toString(nomeArray[k]));
                                    dataset1.addValue(Integer.parseInt(aux)*1000 ,
                                        "Chg", ad.getsStatCurList().get(0).getidList().get(j) + "Id");
                                }
                                
                            } else{
                                dataset1.addValue(Integer.parseInt(ad.getsStatCurList().get(0).getchgList().get(j)),
                                    "Chg", ad.getsStatCurList().get(0).getidList().get(j) + "Id");
                            }
                        }
                        
                        dataset2.addValue(Integer.parseInt(ad.getsStatCurList().get(0).gettempList().get(j)),
                                "T (ºC)", ad.getsStatCurList().get(0).getidList().get(j) + "Id");
                    }
                    final JFreeChart chart = ChartFactory.createBarChart("Consumo de energia nos ultimos " 
                        + ad.getsStatCurList().get(0).getTime() + " segundos",
                        "Dispositivos", "Chg", dataset1,
                        PlotOrientation.VERTICAL, true, true, false
                    );
                    chart.setBackgroundPaint(Color.white);
                    final CategoryPlot plot = chart.getCategoryPlot();
                    plot.setBackgroundPaint(new Color(0xEE, 0xEE, 0xFF));
                    plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
                    plot.mapDatasetToRangeAxis(1, 1);
                    final CategoryAxis domainAxis = plot.getDomainAxis();
                    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
                    final ValueAxis axis2 = new NumberAxis("T (ºC)");
                    plot.setRangeAxis(1, axis2);
                    final LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
                    renderer2.setToolTipGenerator(new StandardCategoryToolTipGenerator());
                    plot.setRenderer(1, renderer2);
                    plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);
                    //Colocando em um painel do proprio swing java
                    ChartPanel CP = new ChartPanel(chart);
                    jPanel1.removeAll();
                    jPanel1.setLayout(new java.awt.BorderLayout());
                    jPanel1.add(CP,BorderLayout.CENTER);
                    jPanel1.validate();
                    break;
                }
            case "Latencia":
                {
                    try {
                        ad.showStatCur();
                    } catch (TokenMgrError ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (FileNotFoundException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (IOException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (ParseException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    }
                    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
                    for(int j=0; j< ad.getsStatCurList().get(0).getidList().size(); j++){
                        dataset.setValue(Float.parseFloat(ad.getsStatCurList().get(0).getlateList().get(j)), 
                                "Latencia", ad.getsStatCurList().get(0).getidList().get(j) + "Id");
                    }
                    JFreeChart chart = ChartFactory.createBarChart("Latencia nos ultimos " 
                            + ad.getsStatCurList().get(0).getTime().toString() + " segundos",
                            "Dispositivos", "Latencia", dataset, 
                            PlotOrientation.VERTICAL, false, true, false);
                    CategoryPlot p = chart.getCategoryPlot();
                    p.setRangeGridlinePaint(Color.black);
                    //Colocando em um painel do proprio swing java
                    ChartPanel CP = new ChartPanel(chart);
                    jPanel1.removeAll();
                    jPanel1.setLayout(new java.awt.BorderLayout());
                    jPanel1.add(CP,BorderLayout.CENTER);
                    jPanel1.validate();
                    break;
                }
            case "Confiabilidade":
                {
                    try {
                        ad.showStatDay();
                    } catch (TokenMgrError ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (FileNotFoundException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (IOException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    } catch (ParseException ex) {
                        System.out.println("[Erro]\n" + ex.toString());
                    }
                    
                    NumberAxis numberaxis = new NumberAxis("Dias");
                    numberaxis.setAutoRangeIncludesZero(false);
                    NumberAxis numberaxis1 = new NumberAxis("Confiabilidade");
                    numberaxis1.setAutoRangeIncludesZero(false);
                    XYSplineRenderer xysplinerenderer = new XYSplineRenderer();
                    
                    XYSeriesCollection xyseriescollection = new XYSeriesCollection();
                    for(int j=0; j< ad.getsStatDayList().size(); j++){
                        System.out.println("aa1");
                        for(int g=0; g< ad.getsStatDayList().get(j).getidList().size() ; g++){
                            System.out.println("aa2");
                            XYSeries xyseries_aux = new XYSeries("Device " + ad.getsStatDayList().get(j).getidDay() + " - " + ad.getsStatDayList().get(j).getidList().get(g));

                            for(int l=0; l< ad.getsStatDayList().get(j).getreliabNetList().size(); l++){
                                String aux1[] = ((String)ad.getsStatDayList().get(j).getreliabNetList().get(l)).split("\\%");
                                if (((aux1[0] != null)&&(!aux1[0].equals("--"))) && (!"-".equals(aux1[0]))){
                                    System.out.println("Olha: " + Float.parseFloat(ad.getsStatDayList().get(j).getidDay()) + " - " + 
                                            Double.parseDouble(aux1[0]));
                                    xyseries_aux.add(Float.parseFloat(ad.getsStatDayList().get(j).getidDay()), 
                                            Double.parseDouble(aux1[0]));
                                }
                            }
                            
                            xyseriescollection.addSeries(xyseries_aux);
                        }
                    }
                    
                    XYPlot xyplot = new XYPlot(xyseriescollection, numberaxis, numberaxis1, xysplinerenderer);
                    xyplot.setBackgroundPaint(Color.lightGray);
                    xyplot.setDomainGridlinePaint(Color.white);
                    xyplot.setRangeGridlinePaint(Color.white);
                    xyplot.setAxisOffset(new RectangleInsets(4D, 4D, 4D, 4D));
                    
                    JFreeChart jfreechart = new JFreeChart("Confiabilidade por dia", JFreeChart.DEFAULT_TITLE_FONT, xyplot, true);
                    ChartUtilities.applyCurrentTheme(jfreechart);
                    
                    ChartPanel CP = new ChartPanel(jfreechart);
                    jPanel1.removeAll();
                    jPanel1.setLayout(new java.awt.BorderLayout());
                    jPanel1.add(CP,BorderLayout.CENTER);
                    jPanel1.validate();
                    break;
                }
        }
    }
}
